Subject: Re: Beginner Question : Filling Arrays from T
Date: 19 Jan 1996 19:18:49 GMT
Organization: OpenVision
Message-ID: <4doqqp$9t8@spanky.pls.ov.com>
References: <1f7cc$13361c.91@news.hampshire.edu>
Reply-To: glenn@ov.com
NNTP-Posting-Host: foghorn.pls.ov.com
In article 91@news.hampshire.edu, <sbfF94@hamp.hampshire.edu> writes:
>Hi, we're writing a cgi program in c to produce a multiple-choice quiz on a web page. The program currently works, but we need to convert the contents of the question and answer arrays from being defined within the code:
This form of initialization only works at compile time. This is because
all of the entries are known, and therefore the size of the array is knowable.
>
>to being filled by an external text file with an indeterminate (and changable) number of entries. We are trying to figure out how to use fread() to do this, but are totally confused as to how. We need to know : a)the required format of the text file to make the entire file readable into the array b) how to get the array "question" to fill itself with as many pointers/strings as are in the text file and c)use the number of entries in the text file to constrain rand().
> Also, how does sizeof() work with fread, and do we need to use it?
>we are compiling on unix using gcc.
> Thanks,
> Shana Furman
> Jon Seagull
>
The simplest possible way to make a dynamic array is to first read in the
strings (with fgets) using dynamic allocation to build a linked list. Once the
linked list is created (and you know the number of entries), you can
allocate the array of pointers and initialize those pointers. Use the following
struct to build your linked list:
struct ll {
char *string_data;
struct ll *forward_pointer;
};
You will need:
struct ll *head, *tail;
to keep track of the head of the list and where to put the next entry.